package com.example.demo.threadDemo.aThreadWithdrawMoney;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description Account
 * @Author songchuanlong
 * @Date 2025-04-14
 */
public class Account {


    //余额
    private double money;
    //卡号
    private String idCard;


    //创建一个lock锁对象
    private final Lock lk=new ReentrantLock();

    @Override
    public String toString() {
        return "Account{" +
                "money=" + money +
                ", idCard='" + idCard + '\'' +
                '}';
    }


    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public String getIdCard() {
        return idCard;
    }

    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }




    public Account() {
    }

    public Account(double money, String idCard) {
        this.money = money;
        this.idCard = idCard;
    }

    //静态方法使用类名.class
    public static void test(){
        synchronized (Account.class){

        }
    }


    /**
     * 要取的钱
     * @param money
     */
    public void drawMoney(double money) {
        //先搞清楚是谁取钱
        String name = Thread.currentThread().getName();
        //防止中间程序崩溃，而此时线程被锁住了，其他线程进不来，使用try-catch-finally
        try {
            //加锁，只允许一个线程进来
            lk.lock();
            //判断余额是否足够
            if(this.money>=money){
                System.out.println(name+"取了"+money);
                this.money-=money;
                System.out.println(name+"取完钱之后还剩下"+this.money);
            }else{
                System.out.println(name+"您的余额不足！");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //解锁
            lk.unlock();
        }
    }
}
